package com.hyfd.service.mp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;








import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageHelper;
import com.hyfd.common.BaseJson;
import com.hyfd.common.GlobalSetHyfd;
import com.hyfd.common.Page;
import com.hyfd.dao.mp.AgentDataDiscountDao;
import com.hyfd.dao.mp.BillPkgDao;
import com.hyfd.dao.mp.DataPkgDao;
import com.hyfd.dao.mp.PhoneSectionDao;
import com.hyfd.dao.mp.AgentBillDiscountDao;
import com.hyfd.dao.mp.ProviderDao;
import com.hyfd.service.BaseService;

@Service
@Transactional
public class PhoneSectionSer extends BaseService {

	public Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private PhoneSectionDao phoneSectionDao;
	@Autowired
	BillPkgDao billPkgDao;
	@Autowired
	DataPkgDao dataPkgDao;
	@Autowired
	ProviderDao providerDao;
	@Autowired
	AgentBillDiscountDao agentBillDiscountDao;
	@Autowired
	AgentDataDiscountDao agentDataDiscountDao;

	/**
	 * 根据主键获取记录
	 * 
	 * @param id
	 * @return
	 */
	public Map<String, Object> getPhoneSectionById(String id) {
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			m = phoneSectionDao.selectByPrimaryKey(id);
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return m;
	}

	/**
	 * 获取记录数量
	 * 
	 * @param m
	 * @return
	 */
	public int getPhoneSectionCount(Map<String, Object> m) {
		int phoneSectionCount = 0;
		try {
			phoneSectionCount = phoneSectionDao.selectCount(m);
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return phoneSectionCount;
	}

	/**
	 * 根据条件分页获取号段折扣模板列表数据并生成json
	 * 
	 * @param req
	 * @return
	 */
	public String phoneSectionList(HttpServletRequest req) {
		StringBuilder sb = new StringBuilder();
		try {
			Map<String, Object> m = getMaps(req); // 封装前台参数为map
			Page p = getPage(m);// 提取分页参数
			int total = getPhoneSectionCount(m);
			p.setCount(total);
			int pageNum = p.getCurrentPage();
			int pageSize = p.getPageSize();

			sb.append("{");
			sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
			sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
			sb.append("" + getKey("records") + ":" + p.getCount() + ",");
			sb.append("" + getKey("rows") + ":" + "");

			PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
			List<Map<String, Object>> dataList = phoneSectionDao.selectAll(m);
			String dataListJson = BaseJson.listToJson(dataList);
			sb.append(dataListJson);
			sb.append("}");
		} catch (Exception e) {
			getMyLog(e, log);
		}

		return sb.toString();
	}

	/**
	 * 批量手机号有效性校验 解析上传的txt文件
	 */

	public String numberBatchFilter(HttpServletRequest req) {
		String txtStr = null;
		String numberMessage = null;
		StringBuilder sBuilder = new StringBuilder();
		MultipartHttpServletRequest re = (MultipartHttpServletRequest) req;
		MultipartFile fileM = re.getFile("numberFile");
		CommonsMultipartFile cf = (CommonsMultipartFile) fileM;
		try {
			InputStream inputStream = cf.getInputStream();
			InputStreamReader reader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(reader);
			while ((txtStr = bufferedReader.readLine()) != null) {
				sBuilder.append(txtStr).append(",");
			}
			reader.close();
			numberMessage = sBuilder.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return numberMessage;
	}

	/**
	 * 检测手机号有效性
	 * */
	public Map<String, Object> checkPhoneMessage(String[] mobileMeg) {
		Map<String, Object> m = new HashMap<String, Object>();
		List<String> phoneMeg = new ArrayList<String>();
		Set<String> faceValue = new HashSet<String>();// 所有充值面值
		for (int i = 0; i < mobileMeg.length; i++) {
			String p = mobileMeg[i];
			String[] num = p.split("-");
			String phone = num[0];
			String value = num[1];
			if (isMobile(phone) || isWLWMobile(phone)) {
				phoneMeg.add(p);
				faceValue.add(value);
			}
		}
		m.put("phoneMessage", phoneMeg);
		m.put("faceValue", faceValue);
		return m;
	}
	
	/**
	 * 批充流量时手机号信息放入各自运营商
	 * */
	public Map<String, Object> distributionByData(List<String> phoneMeg) {
		Map<String, Object> m = new HashMap<String, Object>();
		List<String> yidong = new ArrayList<String>();// 移动的号码
		List<String> liantong = new ArrayList<String>();// 联通的号码
		List<String> dianxin = new ArrayList<String>();// 电信的号码
		String yiDongId="0000000001";
		String lianTongId="0000000002";
		String dianXinId="0000000003";
		for (int i = 0; i < phoneMeg.size(); i++) {
			String p = phoneMeg.get(i);
			String[] num = p.split("-");
			String phone = num[0];
			String section = (phone.length() == 13) ? phone.substring(0, 5)
					: phone.substring(0, 7);// 获取号段
			Map<String, Object> sectionMessage = phoneSectionDao
					.selectBySection(section);
			if (sectionMessage != null) {
				String provider_type = (String) sectionMessage.get("provider_type");
				String province_code = (String) sectionMessage.get("province_code");
				if (provider_type.equals("1")){
					p=p+"-"+province_code;
					yidong.add(p);
				}else if(provider_type.equals("2")){
					p=p+"-"+province_code;
					liantong.add(p);
				}else if(provider_type.equals("3")){
					p=p+"-"+province_code;
					dianxin.add(p);
				}else{
					log.error("没有查询到号段，手机号为"+p);
				}
			} else {
				log.error("没有查询到号段，手机号为"+p);
			}
		}
		m.put(yiDongId, yidong);
		m.put(lianTongId, liantong);
		m.put(dianXinId, dianxin);
		return m;
	}

	/**
	 * 查询虚商话费包和折扣
	 * */
	public List<String> getVirtualBillDiscount(Map<String, Integer> m,
			String agentId, String providerId) {
		List<String> meg = new ArrayList<String>();
		boolean flag=true;
		String result = "";
		Double total = 0.0;
		Double price = 0.0;
		for (Map.Entry<String, Integer> entry : m.entrySet()) {
			Map<String, Object> data = new HashMap<String, Object>();
			String key = entry.getKey();// 包的大小
			Integer value = entry.getValue();// 充值个数
			data.put("providerId", providerId);
			data.put("val", key);
			String billPkgId = billPkgDao.getBillPkgIdByProIdAndValue(data);
			if (billPkgId != null && billPkgId != "") {
				Map<String, String> p = new HashMap<String, String>();
				p.put("agentId", agentId);
				p.put("providerId", providerId);
				p.put("billPkgId", billPkgId);
				Double discount = agentBillDiscountDao.selectDiscount(p);
				if (discount != 0) {
					price = discount * value;//
					if (price != 0.0) {
						total += price;
					}
					result = "<font color=\"green\">" + key
							+ "元</font>的手机号有<font color=\"red\">" + value
							+ "个</font>,折扣价为<font color=\"red\">" + discount
							+ "元</font>，共<font color=\"red\">" + price
							+ "元</font>";
					meg.add(result);
				} else {
					flag=false;
					result = "<font color=\"green\">" + key
							+ "元</font>的手机号有<font color=\"red\">" + value
							+ "个</font>,<font color=\"red\">没有查询到折扣</font>";
					meg.add(result);
				}
			} else {
				flag=false;
				result = "没有可用的<font color=\"red\">" + key + "元</font>的话费包";
				meg.add(result);
			}
		}
		if (flag) {
			meg.add(",总价为<font color=\"red\">" + total + "元</font>");
		} else {
			meg.add(",<font color=\"red\">折扣信息不全,无法计算总价</font>");
		}
		return meg;
	}

	
	/**
	 * 获取三网话费包的折扣信息
	 * */
	public List<String> getThreeBillDiscount(Map<String, Integer> m,
			List<String> pValue, String agentId, String proid) {
		List<String> r= new ArrayList<String>();
		Set<String> result = new HashSet<String>();
		String re = "";
		String countMeg="";
		for (Map.Entry<String, Integer> entry : m.entrySet()) {
			String key = entry.getKey();
			Integer value = entry.getValue();
			countMeg="<font color=\"green\">"+key+ "元</font>的手机号有<font color=\"red\">"+value+"个</font>";
			r.add(countMeg);
		}
		for (int i = 0; i < pValue.size(); i++) {
			String pm = pValue.get(i);
			String[] numMeg = pm.split("-");
			String phone = numMeg[0];
			String value = numMeg[1];
			String section = (phone.length() == 13) ? phone.substring(0, 5)
					: phone.substring(0, 7);// 获取号段
			Map<String, Object> sectionMessage = phoneSectionDao
					.selectBySection(section);

			Map<String, Object> data = new HashMap<String, Object>();
			data.put("providerId", proid);
			data.put("val", value);
			String billPkgId = billPkgDao.getBillPkgIdByProIdAndValue(data);
			if (billPkgId != null && billPkgId != "") {
				String province_code = (String) sectionMessage
						.get("province_code");
				String city_code = (String) sectionMessage.get("city_code");
				Map<String, String> p = new HashMap<String, String>();
				p.put("agentId", agentId);
				p.put("providerId", proid);
				p.put("billPkgId", billPkgId);
				p.put("cityCode", city_code);
				Double discount = agentBillDiscountDao.selectDiscount(p);
				if (discount > 0) {
					re = province_code + city_code + value + "元包折扣价为"
							+ discount + "元";
					result.add(re);
				} else {
					re = province_code + city_code + "没查询到折扣";
					result.add(re);
				}
			}else{
				re = "没有可用的<font color=\"red\">" + value + "元</font>的话费包";
				result.add(re);
			}
		}
		r.add(countMeg+result);
		return r;
	}

	/**
	 * 逗号分隔的电话号码字符串，分割校验后拼接，过滤无效
	 * 
	 * @param str
	 * @return 过滤后的电话号码字符串，逗号拼接
	 */
	public static String mobileFilter(String mobileContent) {
		StringBuilder mobileB = new StringBuilder();
		String[] mobileArr = mobileContent.split(",");
		for (String mobile : mobileArr) {
			if (isMobile(mobile) || isWLWMobile(mobile)) {
				mobileB.append(mobile);
				mobileB.append(",");
			}
		}
		mobileContent = mobileB.toString();
		if (StringUtils.endsWith(mobileContent, ",")) {
			mobileContent = mobileContent.substring(0,
					mobileContent.length() - 1);
		}
		return mobileContent;
	}

	/**
	 * 手机号验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		// p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
		// p =
		// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(14[57])|(17[0])|(18[0,0-9]))\\d{8}$");
		// // 验证手机号
		p = Pattern
				.compile("^((13[0-9])|(15[0-9])|(14[0-9])|(17[0-9])|(18[0-9]))\\d{8}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}

	/**
	 * 物联网卡验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isWLWMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		// p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
		// p =
		// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(14[57])|(17[0])|(18[0,0-9]))\\d{8}$");
		// // 验证手机号
		p = Pattern.compile("^((10648)|(10649))\\d{8}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}

	/**
	 * 是否为正整数
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber1(String str) {
		Pattern pattern = Pattern.compile("\\d+");
		return pattern.matcher(str).matches();
	}

	/**
	 * 是否为正整数或负整数
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber2(String str) {
		Pattern pattern = Pattern.compile("-?\\d+");
		return pattern.matcher(str).matches();
	}

	/**
	 * 电话号码验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isPhone(String str) {
		Pattern p1 = null, p2 = null;
		Matcher m = null;
		boolean b = false;
		p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
		p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
		if (str.length() > 9) {
			m = p1.matcher(str);
			b = m.matches();
		} else {
			m = p2.matcher(str);
			b = m.matches();
		}
		return b;
	}

	/**
	 * @功能描述： 根据条件获取全部号段折扣模板列表数据并生成json
	 *
	 * @作者：zhangpj @创建时间：2016年12月16日
	 * @param req
	 * @return
	 */
	public String phoneSectionAllList(HttpServletRequest req) {
		String str = null;
		try {
			Map<String, Object> m = getMaps(req); // 封装前台参数为map
			List<Map<String, Object>> dataList = phoneSectionDao.selectAll(m);
			str = BaseJson.listToJson(dataList);
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return str;
	}

	/**
	 * 添加号段折扣模板信息
	 * 
	 * @param req
	 * @return
	 */
	public String phoneSectionAdd(HttpServletRequest req) {
		Session session = getSession();
		boolean flag = false;
		try {
			Map<String, Object> myData = getMaps(req);
			Map<String, Object> userInfoMap = getUser(); // 取到当前用户信息
			myData.put("createUser", userInfoMap.get("suName"));// 放入用户
			int rows = phoneSectionDao.insert(myData);
			if (rows > 0) {
				flag = true;
			}
			session.setAttribute(GlobalSetHyfd.backMsg, flag ? "添加成功" : "添加失败");
		} catch (Exception e) {
			session.setAttribute(GlobalSetHyfd.backMsg,
					"小Y不小心感冒了,号段添加失败,请稍后重试!");
			getMyLog(e, log);
		}
		return "redirect:/phoneSectionListPage";
	}

	/**
	 * 修改号段折扣模板信息
	 * 
	 * @param req
	 * @param id
	 * @return
	 */
	public String phoneSectionEdit(HttpServletRequest req, String id) {

		try {
			boolean flag = false;
			Map<String, Object> myData = getMaps(req);
			Map<String, Object> userInfoMap = getUser(); // 取到当前用户信息
			myData.put("updateUser", userInfoMap.get("suName"));// 放入用户
			int rows = phoneSectionDao.updateByPrimaryKeySelective(myData);
			if (rows > 0) {
				flag = true;
			}
			Session session = getSession();
			session.setAttribute(GlobalSetHyfd.backMsg, flag ? "修改成功" : "修改失败");
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return "phoneSectionListPage";
	}

	/**
	 * 跳转到号段折扣模板编辑页
	 * 
	 * @param id
	 * @return
	 */
	public String phoneSectionEditPage(String id) {
		try {
			Map<String, Object> phoneSection = getPhoneSectionById(id);
			Session session = getSession();
			session.setAttribute("phoneSection", phoneSection);
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return "mp/phoneSectionEdit";
	}

	/**
	 * 带着模板Id跳转到号段折扣模板详情页
	 * 
	 * @param id
	 * @return
	 */
	public String phoneSectionDetail(String id) {
		try {
			Map<String, Object> m = getPhoneSectionById(id);
			Session session = getSession();
			session.setAttribute("phoneSection", m);
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return "mp/phoneSectionDetail";
	}

	/**
	 * 删除号段折扣模板信息
	 * 
	 * @param id
	 * @return
	 */
	public String phoneSectionDel(String id) {

		try {
			boolean flag = false;
			int rows = phoneSectionDao.deleteByPrimaryKey(id);
			if (rows > 0) {
				flag = true;
			}

			Session session = getSession();
			session.setAttribute(GlobalSetHyfd.backMsg, flag ? "删除成功" : "删除失败");

		} catch (Exception e) {
			getMyLog(e, log);
		}
		return "phoneSectionListPage";
	}
}
